<script>
import { versionUpdate } from '@/services/user';

export default {
  onLaunch() {
    //检查版本升级及下载安装apk自动升级
    // #ifdef APP-PLUS
    this.checkUpdate(plus.runtime.version);

    //缓存共用本地存储变量
    uni.setStorageSync(
      'DeviceId' + process.env.VUE_APP_PLATFORMID,
      uni.getSystemInfoSync().deviceId
    );
    uni.setStorageSync(
      'TerminalType' + process.env.VUE_APP_PLATFORMID,
      'android'
    );
    uni.setStorageSync(
      'Version' + process.env.VUE_APP_PLATFORMID,
      plus.runtime.version
    );
    // #endif
  },
  methods: {
    //版本号检查&检查更新
    async checkUpdate(version) {
      const { code, data } = await versionUpdate({ version });
      if (code != 200) return;
      //console.log(code, data);
      if (data.update) {
        this._download(data.url);
      }
    },
    //下载方法
    _download(url) {
      const dtask = plus.downloader.createDownload(url, {}, (d, status) => {
        //console.log(d, status);
        uni.showToast({
          title: '下载完成',
          icon: 'none',
        });
        if (status == 200) {
          plus.runtime.install(
            plus.io.convertLocalFileSystemURL(d.filename),
            {},
            () => {
              uni.showToast({
                title: '下载成功',
                icon: 'none',
              });
            },
            () => {
              uni.showToast({
                title: '安装失败-01',
                icon: 'none',
              });
            }
          );
        } else {
          uni.showToast({
            title: '更新失败-02',
            icon: 'none',
          });
        }
      });
      try {
        const loading = plus.nativeUI.showWaiting('正在下载', {
          back: 'none',
        });
        dtask.start();
        dtask.addEventListener('statechanged', (task, status) => {
          switch (task.state) {
            case 3:
              {
                const { downloadedSize, totalSize } = task;
                const progress = parseInt((downloadedSize / totalSize) * 100);
                loading.setTitle(`正在下载${progress}%`);
              }
              break;
            case 4:
              plus.nativeUI.closeWaiting();
              break;
          }
        });
      } catch {
        plus.nativeUI.closeWaiting();
        uni.showToast({
          title: '更新失败-03',
          icon: 'none',
        });
      }
    },
  },
};
</script>

<style lang="scss">
@import './static/fonts/iconfont.css';
@import 'tailwindcss/utilities';
@import 'uview-ui/index.scss';

*,
::before,
::after {
  box-sizing: border-box;
  border-width: 0;
  border-style: solid;
  border-color: currentColor;
}

//2025.02.14
.border-b-gray {
  border-bottom: 2rpx solid #ccc;
}
</style>
